package net.chasing.androidbaseconfig.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import net.chasing.androidbaseconfig.BaseApplication;
import net.chasing.androidbaseconfig.R;
import net.chasing.androidbaseconfig.util.permission.PermissionUtils;

import java.io.File;

public class SystemPageOpenUtils {

    public static void goBackHome(Activity activity) {
        Intent backHome = new Intent(Intent.ACTION_MAIN)
                .addCategory(Intent.CATEGORY_HOME)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(backHome);
    }

    //打开系统设置界面
    public static void goToSetting(Activity activity) {
        activity.startActivity(new Intent(Settings.ACTION_SETTINGS));
        BaseApplication.isOpenSystemPage = true;
    }

    //打开应用设置界面
    public static void goToApplicationSetting(Activity activity) {
        try {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + activity.getPackageName()));
            activity.startActivity(intent);
            BaseApplication.isOpenSystemPage = true;
        } catch (Exception ignored) {
        }
    }

    //拨打电话
    public static void callPhone(Context context, String telPhone) {
        try {
            if (PermissionUtils.requestPermission((FragmentActivity) context, isAllGranted -> {
                if (isAllGranted)
                    callPhone(context, telPhone);
            }, Manifest.permission.CALL_PHONE))
                return;

            // Intent.A-CTION_CALL直接拨打    Intent.ACTION_DIAL跳转后用户点击拨打
            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri data = Uri.parse("tel:" + telPhone);
            intent.setData(data);
            context.startActivity(intent);
            BaseApplication.isOpenSystemPage = true;
        } catch (Exception e) {
            ToastUtils.showShort(context, R.string.base_call_phone_fail);
        }
    }

    public static void goToNotificationSetting(Activity activity) {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {// android 8.0引导
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("android.provider.extra.APP_PACKAGE", activity.getPackageName());
        } else { // android 5.0-7.0
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", activity.getPackageName());
            intent.putExtra("app_uid", activity.getApplicationInfo().uid);
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
    }

    public static final int REQUEST_CODE_TAKE_PHOTO = 101;//拍照标识
    public static final int REQUEST_CODE_CROP_PHOTO = 102;//照片剪切标识
    public static final int REQUEST_CODE_SELECT_VIDEO = 103;//选择视频
    public static final int REQUEST_CODE_SELECT_FILE = 104;//选择文件
    public static final int REQUEST_CODE_SELECT_PIC = 105;//选择图片
    public static final int REQUEST_CODE_SELECT_AUDIO = 106;//选择音频
    public static final int REQUEST_CODE_AUDIO_RECORD = 107;//录制音频
    public static final int REQUEST_CODE_VIDEO_RECORD = 108;//录制视频

    // region 拍照
    public static String takePhoto(FragmentActivity activity) {
        return takePhoto(activity, null, FileUtils.getTempPath(activity) + FileUtils.getPhotoFileName());
    }

    public static String takePhoto(FragmentActivity activity, Fragment fragment) {
        return takePhoto(activity, fragment, FileUtils.getTempPath(activity) + FileUtils.getPhotoFileName());
    }

    public static String takePhoto(FragmentActivity activity, String filePath) {
        return takePhoto(activity, null, filePath);
    }

    public static String takePhoto(FragmentActivity activity, Fragment fragment, String filePath) {
        if (PermissionUtils.requestStoragePermission(activity, isAllGranted -> {
            if (isAllGranted)
                takePhoto(activity, fragment, filePath);
        }, Manifest.permission.CAMERA))
            return null;
        try {
            Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            Uri uri = FileUtils.getFileUri(activity, filePath);
            if (uri != null) {
                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                if (fragment != null)
                    fragment.startActivityForResult(takePhotoIntent, REQUEST_CODE_TAKE_PHOTO);
                else
                    activity.startActivityForResult(takePhotoIntent, REQUEST_CODE_TAKE_PHOTO);
                BaseApplication.isOpenSystemPage = true;
                return filePath;
            }
        } catch (Exception e) {
            ToastUtils.showShort(activity, activity.getResources().getString(R.string.base_photo_can_not_write));
        }
        return null;
    }
    // endregion

    // region 图片裁剪
    //裁剪图片方法实现--任意宽高
    public static String beginCrop(Activity activity, String picPath) {
        return beginCrop(activity, picPath, 0, 0, 0, 0, false);
    }

    public static String beginCropHeadImg(Activity activity, String picPath) {
        return beginCropHeadImg(activity, picPath, 0);
    }

    /**
     * 裁剪图片方法实现--裁剪头像，限制了宽高接近1：1（注：裁剪比例直接设置为1:1，则部分手机裁剪的显示框会变成圆形）
     *
     * @param activity
     * @param picPath
     * @param outputSize 图片输出宽高尺寸
     * @return
     */
    public static String beginCropHeadImg(Activity activity, String picPath, int outputSize) {
        return beginCrop(activity, picPath, 100, 101, outputSize, outputSize);
    }

    //裁剪图片方法实现--widthRatio/heightRatio为裁剪的宽高比
    public static String beginCrop(Activity activity, String picPath, int widthRatio, int heightRatio) {
        return beginCrop(activity, picPath, widthRatio, heightRatio, 0, 0);
    }

    public static String beginCrop(Activity activity, String picPath, int widthRatio, int heightRatio,
                                   int outputX, int outputY) {
        return beginCrop(activity, picPath, widthRatio, heightRatio, outputX, outputY, false);
    }

    public static String beginCrop(Activity activity, String picPath, int widthRatio, int heightRatio,
                                   int outputX, int outputY, boolean copyToCache) {
        if (!FileUtils.exists(activity, picPath)) {
            ToastUtils.showShort(activity, R.string.base_uncheck_this_photo);
            return null;
        }
        try {
            if (copyToCache)
                picPath = FileUtils.getOperationalFilePath(activity, picPath);
            Uri uri = FileUtils.getFileUri(activity, picPath);
            if (uri != null) {
                Intent intent = new Intent("com.android.camera.action.CROP");
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(uri, "image/*");
                intent.putExtra("crop", "true");// crop=true 有这句才能出来最后的裁剪页面.
                if (widthRatio > 0 && heightRatio > 0) {
                    intent.putExtra("aspectX", widthRatio);// 这两项为裁剪框的比例.
                    intent.putExtra("aspectY", heightRatio);// x:y=1:1
                }
                if (outputX > 0 && outputY > 0) {
                    // 是裁剪图片宽高，注意如果return-data=true情况下,其实得到的是缩略图，并不是真实拍摄的图片大小，
                    // 而原因是拍照的图片太大，所以这个宽高当你设置很大的时候发现并不起作用，就是因为返回的原图是缩略图，但是作为头像还是够清晰了
                    intent.putExtra("outputX", outputX);//图片输出大小
                    intent.putExtra("outputY", outputY);
                }
                intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
                intent.putExtra("circleCrop", widthRatio > 0 && widthRatio == heightRatio);//设置裁剪框是否圆形，部分手机支持

                String path;
                Uri uriTempFile = FileUtils.getDownloadPicUri(activity, FileUtils.getPhotoFileName());
                path = FileUtils.getFilePathByUri(activity, uriTempFile);
                // 部分机型获取path异常，则尝试别的方式：
                if (path != null)
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uriTempFile);
                else if (Build.VERSION.SDK_INT >= 30) {
                    //android 11以上，将文件创建在公有目录
                    path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
                    //storage/emulated/0/Pictures
                    File file = new File(path, System.currentTimeMillis() + ".png");
                    path = file.getPath();
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse("file://" + file.getAbsolutePath()));
                } else {
                    //storage/emulated/0/Android/data/com.xxxxx/cache
                    path = FileUtils.getExternalAppCachePath(activity, "crop_img");
                    File file = new File(path, System.currentTimeMillis() + ".png");
                    path = file.getPath();
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse("file://" + file.getAbsolutePath()));
                }
                activity.startActivityForResult(intent, REQUEST_CODE_CROP_PHOTO);
                return path;
            }
        } catch (Exception e) {
            if (!copyToCache && e.getMessage() != null && e.getMessage().contains("not have permission"))
                return beginCrop(activity, picPath, widthRatio, heightRatio, outputX, outputY, true);
            else
                ToastUtils.showShort(activity, activity.getResources().getString(R.string.base_photo_can_not_write) + e.getMessage());
        }
        return null;
    }
    // endregion

    // region 图片、视频、音频、系统文件选择界面
    //打开系统图片选择界面
    public static void openPicSelectActivity(FragmentActivity activity) {
        openPicSelectActivity(activity, null);
    }

    public static void openPicSelectActivity(FragmentActivity activity, Fragment fragment) {
        if (PermissionUtils.requestStoragePermission(activity, isAllGranted -> {
            if (isAllGranted)
                openPicSelectActivity(activity, fragment);
        })) return;

        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        if (fragment != null)
            fragment.startActivityForResult(Intent.createChooser(intent, "选择要上传的图片"), REQUEST_CODE_SELECT_PIC);
        else
            activity.startActivityForResult(Intent.createChooser(intent, "选择要上传的图片"), REQUEST_CODE_SELECT_PIC);
        BaseApplication.isOpenSystemPage = true;


        //Android13支持：
//        final int maxNumPhotosAndVideos = 4;
//        Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
//        intent.putExtra(MediaStore.EXTRA_PICK_IMAGES_MAX, maxNumPhotosAndVideos);
//        activity.startActivityForResult(intent, REQUEST_CODE_SELECT_PIC);
    }

    //打开系统视频选择界面
    public static void openVideoSelectActivity(FragmentActivity activity) {
        openVideoSelectActivity(activity, null);
    }

    public static void openVideoSelectActivity(FragmentActivity activity, Fragment fragment) {
        if (PermissionUtils.requestStoragePermission(activity, isAllGranted -> {
            if (isAllGranted)
                openVideoSelectActivity(activity, fragment);
        })) return;

        Intent intent = new Intent();
        intent.setType("video/*");
        intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        if (fragment != null)
            fragment.startActivityForResult(Intent.createChooser(intent, "选择要导入的视频"), REQUEST_CODE_SELECT_VIDEO);
        else
            activity.startActivityForResult(Intent.createChooser(intent, "选择要导入的视频"), REQUEST_CODE_SELECT_VIDEO);
        BaseApplication.isOpenSystemPage = true;
    }

    //打开系统录制视频界面
    public static void openVideoRecordActivity(FragmentActivity activity, String savePath, int timeDuration) {
        openVideoRecordActivity(activity, null, savePath, timeDuration);
    }

    public static void openVideoRecordActivity(FragmentActivity activity, Fragment fragment, String savePath, int timeDuration) {
        if (PermissionUtils.requestStoragePermission(activity, isAllGranted -> {
            if (isAllGranted)
                openVideoRecordActivity(activity, fragment, savePath, timeDuration);
        }, Manifest.permission.CAMERA)) return;

        Uri uri = FileUtils.getFileUri(activity, savePath);
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // 设置视频录制的质量，0为低质量，1为高质量。
//        intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT,10485760L); // 指定视频最大允许的尺寸，单位为byte。
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); // 设置媒体文件的保存路径。
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, timeDuration); // 设置视频最大允许录制的时长，单位为秒。
        if (fragment != null)
            fragment.startActivityForResult(intent, REQUEST_CODE_VIDEO_RECORD);
        else
            activity.startActivityForResult(intent, REQUEST_CODE_VIDEO_RECORD);
        BaseApplication.isOpenSystemPage = true;
    }

    //打开系统音频选择界面
    public static void openAudioSelectActivity(FragmentActivity activity) {
        openAudioSelectActivity(activity, null);
    }

    public static void openAudioSelectActivity(FragmentActivity activity, Fragment fragment) {
        if (PermissionUtils.requestStoragePermission(activity, isAllGranted -> {
            if (isAllGranted)
                openAudioSelectActivity(activity, fragment);
        })) return;

        Intent intent = new Intent();
        intent.setType("audio/*");
        intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        if (fragment != null)
            fragment.startActivityForResult(Intent.createChooser(intent, "选择要导入的音频"), REQUEST_CODE_SELECT_AUDIO);
        else
            activity.startActivityForResult(Intent.createChooser(intent, "选择要导入的音频"), REQUEST_CODE_SELECT_AUDIO);
        BaseApplication.isOpenSystemPage = true;
    }

    //打开系统文件选择界面
    public static void openFileSelectActivity(FragmentActivity activity) {
        openFileSelectActivity(activity, null);
    }

    public static void openFileSelectActivity(FragmentActivity activity, Fragment fragment) {
        if (activity == null || PermissionUtils.requestStoragePermission(activity, isAllGranted -> {
            if (isAllGranted)
                openFileSelectActivity(activity, fragment);
        })) return;

        Intent intent = new Intent();
//        StringBuilder sb = new StringBuilder();
//        String[] mimeTypeList = new String[CHOOSE_FILE_TYPE_LIST.length];
//        for (int i = 0; i < CHOOSE_FILE_TYPE_LIST.length; i++) {
//            mimeTypeList[i] = FileTypeUtils.getMIMEType(CHOOSE_FILE_TYPE_LIST[i]);
//            sb.append(mimeTypeList[i]).append("|");
//        }
//        if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1);
//        intent.setType(sb.toString());
        intent.setType("*/*");
//        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypeList);
        intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        if (fragment != null)
            fragment.startActivityForResult(Intent.createChooser(intent, "选择要上传的文件"), REQUEST_CODE_SELECT_FILE);
        else
            activity.startActivityForResult(Intent.createChooser(intent, "选择要上传的文件"), REQUEST_CODE_SELECT_FILE);
        BaseApplication.isOpenSystemPage = true;
    }
    // endregion

    //打开系统录音界面
    public static void openAudioRecordActivity(FragmentActivity activity) {
        openAudioRecordActivity(activity, null);
    }

    public static void openAudioRecordActivity(FragmentActivity activity, Fragment fragment) {
        if (PermissionUtils.requestStoragePermission(activity, isAllGranted -> {
            if (isAllGranted)
                openAudioRecordActivity(activity, fragment);
        }, Manifest.permission.MODIFY_AUDIO_SETTINGS))
            return;
        //设置intent的属性为录音设置
        try {
            Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
            if (fragment != null)
                fragment.startActivityForResult(intent, REQUEST_CODE_AUDIO_RECORD);
            else
                activity.startActivityForResult(intent, REQUEST_CODE_AUDIO_RECORD);
            BaseApplication.isOpenSystemPage = true;
        } catch (Exception e) {
            ToastUtils.showShort(activity, R.string.base_uncheck_audio_app);
        }
    }

    // 打开外部浏览器
    public static void openOutsideWebView(Activity activity, String url) {
        Uri content_url = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, content_url);
        activity.startActivity(intent);
    }
}
